package com.pzy.base.filter;

import java.io.IOException;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.druid.support.json.JSONUtils;
import com.pzy.base.util.HttpServletRequestUtil;
import com.pzy.base.util.RequestBodyContextUtil;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 自定义过滤器, 用于将rquest body信息存入 ThreadLocal 中, 方便后续读取
 */
@Order(1)
@Component
@WebFilter(filterName = "RequestBodyFilter")
public class RequestBodyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (HttpServletRequestUtil.isMultipartRequest(request)) {
            RequestBodyContextUtil.setParam(JSONUtils.toJSONString(request.getParameterMap()));
            try {
                chain.doFilter(request, response);
            } finally {
                RequestBodyContextUtil.remove();
            }
            return;
        }

        if (HttpServletRequestUtil.isJsonRequest(request)) {
            RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
            String json = new String(requestWrapper.getBody());
            RequestBodyContextUtil.setParam(json);
            try {
                chain.doFilter(requestWrapper, response);
            } finally {
                RequestBodyContextUtil.remove();
            }
            return;
        }

        chain.doFilter(request, response);
    }

}
